package com.yimi.appstore.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yimi.appstore.R;
import com.yimi.appstore.fileexplorer.FileCategoryHelper;
import com.yimi.appstore.fileexplorer.FileCategoryHelper.FileCategory;
import com.yimi.appstore.fileexplorer.FileIconHelper;
import com.yimi.appstore.fileexplorer.FileInfo;
import com.yimi.appstore.util.FileUtils;
import com.yimi.appstore.util.IntentBuilder;
import com.yimi.appstore.util.Util;

public class CategoryFileActivity extends Activity implements OnCheckedChangeListener, OnClickListener {

	private static final String TAG = "CategoryFileActivity";
	public static final int VIDEO = 1;
	public static final int PICTURE = 2;
	public static final int MUSIC = 3;
	public static final int NOVEL = 4;
	private Context mContext;
	private FileCategory fc;
	private ArrayList<FileInfo> fileInfos = new ArrayList<FileInfo>();
	private ExpandableListView fileListView;
	private FileListAdapter fileListAdapter;

	private RelativeLayout checkboxRl;
	private CheckBox allSelectedcb;
	private Button deleteBtn, cancleBtn;
	private TextView selectedCountTv;
	private ProgressDialog progressDialog;
	private ArrayList<FileInfo> selectedFiles = new ArrayList<FileInfo>();

	public static void lanuchActivity(Context cx, FileCategory fc) {
		Intent i = new Intent(cx, CategoryFileActivity.class);
		i.putExtra("fileType", fc);
		cx.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.file_explorer_layout);
		initUi();
		getData();
		initListener();
	}

	private void initUi() {
		mContext = this;
		checkboxRl = (RelativeLayout) findViewById(R.id.checkbox_rl);
		selectedCountTv = (TextView) findViewById(R.id.selected_count_tv);
		allSelectedcb = (CheckBox) findViewById(R.id.all_check);
		deleteBtn = (Button) findViewById(R.id.unistall_apk_btn);
		cancleBtn = (Button) findViewById(R.id.cancle_checkbox_btn);
		fileListView = (ExpandableListView) findViewById(R.id.file_path_list);
		fileListView.setGroupIndicator(null);
	}

	private void getData() {
		Intent data = getIntent();
		if (data != null) {
			fc = (FileCategory) data.getSerializableExtra("fileType");
			boolean sdCardReady = Util.isSDCardReady();
			if (sdCardReady) {
				FileCategoryHelper categoryHelper = new FileCategoryHelper(mContext);
				Cursor cursor = categoryHelper.query(fc);
				if (cursor != null) {
					while (cursor.moveToNext()) {
						FileInfo fileInfo = new FileInfo();
						fileInfo.dbId = cursor.getLong(FileCategoryHelper.COLUMN_ID);
						fileInfo.filePath = cursor.getString(FileCategoryHelper.COLUMN_PATH);
						fileInfo.fileName = Util.getNameFromFilepath(fileInfo.filePath);
						fileInfo.fileSize = cursor.getLong(FileCategoryHelper.COLUMN_SIZE);
						fileInfo.ModifiedDate = cursor.getLong(FileCategoryHelper.COLUMN_DATE) * 1000;
						fileInfos.add(fileInfo);
					}
					fileListView.setVisibility(View.VISIBLE);
					if (fileListAdapter == null) {
						fileListAdapter = new FileListAdapter(mContext, fileInfos);
						fileListView.setAdapter(fileListAdapter);
					} else {
						fileListAdapter.updateListData(fileInfos);
					}

				} else {
					showView(R.id.empty_view, true);
				}

			} else {
				showView(R.id.sd_not_available_page, true);
			}

		} else {
			showView(R.id.empty_view, true);
		}

	}

	private void initListener() {
		findViewById(R.id.go_back_btn).setOnClickListener(this);
		allSelectedcb.setOnCheckedChangeListener(this);
		cancleBtn.setOnClickListener(this);
		deleteBtn.setOnClickListener(this);
	}

	private void showEmptyView(boolean show) {
		View emptyView = findViewById(R.id.empty_view);
		if (emptyView != null)
			emptyView.setVisibility(show ? View.VISIBLE : View.GONE);
	}

	private void showView(int id, boolean show) {
		View view = findViewById(id);
		if (view != null) {
			view.setVisibility(show ? View.VISIBLE : View.GONE);
		}
	}

	private class FileListAdapter extends BaseExpandableListAdapter {

		protected Context context;
		protected List<FileInfo> listData;
		protected LayoutInflater lInflater;
		protected FileIconHelper iconHelper;

		public FileListAdapter(Context context, List<FileInfo> listData) {
			this.context = context;
			this.listData = listData;
			this.lInflater = LayoutInflater.from(context);
			iconHelper = new FileIconHelper(context);
		}

		/**
		 * 更新适配器数据
		 * 
		 * @param listData
		 */
		public void updateListData(List<FileInfo> listData) {
			this.listData = listData;
			this.notifyDataSetChanged();
		}

		/**
		 * 获取适配器数据
		 * 
		 * @return
		 */
		public List<FileInfo> getListData() {
			return this.listData;
		}

		class ViewHolder implements OnClickListener {
			ImageView lFileImage, lFileImageFrame;
			ImageView checkbox;
			TextView fileName, modifiedTime, fileSize, options;
			int position = -1;

			@Override
			public void onClick(View v) {
				if (position != -1) {
					final FileInfo info = listData.get(position);
					info.Selected = !info.Selected;
					if (info.Selected) {
						selectedFiles.add(info);
						checkbox.setImageResource(R.drawable.mzw_settings_check);
					} else {
						selectedFiles.remove(info);
						checkbox.setImageResource(R.drawable.mzw_settings_uncheck);
					}
					selectedCountTv.setText("已选中" + selectedFiles.size() + "个");
					showToparea();
				}

			}

		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return null;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
				ViewGroup parent) {
			return getGenericView();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return listData.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return listData.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			final FileInfo info = listData.get(groupPosition);
			View v = convertView;
			ViewHolder vh = null;
			if (v == null || v.getTag() == null) {
				v = lInflater.inflate(R.layout.category_file_item_layout, null);
				vh = new ViewHolder();
				vh.lFileImage = (ImageView) v.findViewById(R.id.file_image);
				vh.lFileImageFrame = (ImageView) v.findViewById(R.id.file_image_frame);
				vh.fileName = (TextView) v.findViewById(R.id.file_name);
				vh.modifiedTime = (TextView) v.findViewById(R.id.modified_time);
				vh.fileSize = (TextView) v.findViewById(R.id.file_size);
				vh.options = (TextView) v.findViewById(R.id.tv_options);
				vh.checkbox = (ImageView) v.findViewById(R.id.file_checkbox);
				v.setTag(vh);
			} else {
				vh = (ViewHolder) v.getTag();
			}
			vh.position = groupPosition;
			vh.fileName.setText(info.fileName);
			vh.fileSize.setText(Util.convertStorage(info.fileSize));
			vh.modifiedTime.setText(Util.formatDateString(context, info.ModifiedDate));
			if (info.Selected) {
				vh.checkbox.setImageResource(R.drawable.mzw_settings_check);
			} else {
				vh.checkbox.setImageResource(R.drawable.mzw_settings_uncheck);
			}
			if (fc == FileCategory.Picture) {
				vh.options.setText("查看");
				vh.options.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.aa_button_stop_pressed, 0, 0);

			} else {
				vh.options.setText("播放");
				vh.options.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.aa_button_play_normal, 0, 0);
			}
			vh.options.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					IntentBuilder.viewFile(mContext, info.filePath);
				}
			});
			if (info.IsDir) {
				vh.lFileImageFrame.setVisibility(View.GONE);
				vh.lFileImage.setImageResource(R.drawable.folder);
			} else {
				iconHelper.setIcon(info, vh.lFileImage, vh.lFileImageFrame);
			}
			vh.checkbox.setOnClickListener(vh);
			return v;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		public View getGenericView() {
			View view = lInflater.inflate(R.layout.apk_installed_bottom_layout, null);
			return view;
		}

	}

	private void doOperationDelete(final ArrayList<FileInfo> selectedFileList) {
		final ArrayList<FileInfo> selectedFiles = new ArrayList<FileInfo>(selectedFileList);
		Dialog dialog = new AlertDialog.Builder(mContext)
				.setMessage(mContext.getString(R.string.operation_delete_confirm_message))
				.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						new DeleteFileTask().execute();
					}
				}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						clearSelection();
					}
				}).create();
		dialog.show();
	}

	/**
	 * 显示顶部area
	 */
	private void showToparea() {
		if (!selectedFiles.isEmpty() && checkboxRl.getVisibility() != View.VISIBLE) {
			checkboxRl.setVisibility(View.VISIBLE);
		} else if (selectedFiles.isEmpty() && checkboxRl.getVisibility() == View.VISIBLE) {
			checkboxRl.setVisibility(View.GONE);
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			selectedFiles.clear();
			for (FileInfo info : fileInfos) {
				info.Selected = true;
				selectedFiles.add(info);
			}
			selectedCountTv.setText("已选中" + selectedFiles.size() + "个");
			fileListAdapter.notifyDataSetChanged();
		} else {
			clearSelection();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.go_back_btn:
			finish();
			break;

		case R.id.unistall_apk_btn:
			doOperationDelete(selectedFiles);
			break;

		case R.id.cancle_checkbox_btn:
			clearSelection();
			break;
		}
	}

	private void clearSelection() {
		selectedFiles.clear();
		for (FileInfo info : fileInfos) {
			info.Selected = false;
		}
		checkboxRl.setVisibility(View.GONE);
		fileListAdapter.notifyDataSetChanged();
	}

	private void showProgress(String msg) {
		progressDialog = new ProgressDialog(mContext);
		// dialog.setIcon(R.drawable.icon);
		progressDialog.setMessage(msg);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	class DeleteFileTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showProgress(mContext.getString(R.string.operation_deleting));
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			boolean result = false;
			for (FileInfo f : selectedFiles) {
				result = FileUtils.DeleteFile(f);
				if (!result)
					break;
				fileInfos.remove(f);
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			if (!result)
				Toast.makeText(mContext, "一不小心删除失败了T_T", Toast.LENGTH_SHORT).show();
			clearSelection();
			notifyFileSystemChanged(Environment.getExternalStorageDirectory().getAbsolutePath());
		}
	}

	private void notifyFileSystemChanged(String path) {
		mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
				+ path)));
	}
}
